package com.ashleyleung.jetpack_b_station.musicList

import android.os.Bundle
import androidx.lifecycle.Observer
import com.ashleyleung.jetpack_b_station.R
import com.ashleyleung.jetpack_b_station.base.BaseActivity
import com.ashleyleung.jetpack_b_station.player.domain.Music
import kotlinx.android.synthetic.main.activity_music.*
import timber.log.Timber

/**
 * @author lxy
 * @name
 * @class describe
 * @date 2022-06-22
 *
 */
class MusicActivity : BaseActivity() {
    private lateinit var mForeverObserver: ForeverObserver


    private val musicPresenter by lazy {
        MusicPresenter(this)
    }

//    init{
// //       addLifeListener(musicPresenter)
//        lifeProvider.addLifeListener(musicPresenter)
//    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_music)
        initDataListener()
        initListener()
    }


    inner class ForeverObserver : Observer<List<Music>> {
        override fun onChanged(result: List<Music>?) {
            Timber.e("ForeverObserver data change ---> ${result?.size}")
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        musicPresenter.liveMusicList.removeObserver(mForeverObserver)
    }

    //监听数据变化
    private fun initDataListener() {

        /**
         * 在view层对LiveData添加监听方式2种
         * */
        //
//      方式一：   直接用lifecycle监听Activity或fragment是否活跃更新页面
        musicPresenter.liveMusicList.observe(this,Observer {
            Timber.e("live data music updated...")
            Timber.e("live data musicList --->  ${it?.size}")
            var str = "live data加载到了-->  ${it?.size}条数据"
            tvMusicNum?.text = str

        })
        //      方式二： 自己写一个ForeverObserver 监听，需要onDestroy的时候移除 任意状态都会更新
        mForeverObserver = ForeverObserver()
        musicPresenter.liveMusicList.observeForever(mForeverObserver)

//================下面这种是自己写到的监听

        musicPresenter.musicList.addListener(this) {
            Timber.e(Thread.currentThread().name)
            Timber.e("musicList --->  ${it?.size}")
            var str = "加载到了-->  ${it?.size}条数据"
            tvMusicNum?.text = str
        }
        musicPresenter.loadState.addListener(this) {
            Timber.e("加载状态 --->  $it")
        }
    }

    private fun initListener() {
        btn_get_music_list.setOnClickListener {
            musicPresenter.getMusic()
        }
    }
}